//
//  OrderDetailVC.swift
//  BaseSwift
//
//  Created by gh on 2019/10/5.
//  Copyright © 2019 ghwang. All rights reserved.
//

import UIKit

class OrderDetailVC: UIViewController {

    let bgScr = UIScrollView()
    var order:OrderVo?
    let tlab = UILabel()
    let cancelBtn = UIButton()
    let rightBtn = UIButton()


    
    lazy var orderInfoView:UIView = {
        
        let bg:UIView = UIView()
        bg.backgroundColor = UIColor.white
        bg.sd_cornerRadius = SMALL_BTN_RADIUS

        let titlab = UILabel()
        titlab.text = "订单信息"
        titlab.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(rawValue: 0.2))
        titlab.textColor = UIColor.black
        bg.addSubview(titlab)
        
        let _  = titlab.sd_layout()?.leftSpaceToView(bg,16)!.heightIs(22)!.topSpaceToView(bg,5)!.rightSpaceToView(bg,16)
        

        
        let time = self.order?.createTime?.split(string: "T").first
        let time1 = self.order?.createTime?.split(string: "T")[1].split(string: ".").first
        let time2 = time! + " "+time1!
        var arr = [["title":"支付方式","value":Constant.getPayType(status: self.order!.payType)],
                   ["title":"订单编号","value":self.order!.orderNo!],
                   ["title":"下单时间","value":time2],
                   ["title":"备注信息","value":self.order?.remark ?? ""],


                  ]
        
        
    
        let infoView  = self.createVeiwWithArray(tits: arr )
       bg.addSubview(infoView)
        let _ = infoView.sd_layout()?.topSpaceToView(bg,40)?.autoHeightRatio(0)?.widthRatioToView(bg,1)
       bg.setupAutoHeight(withBottomView: infoView, bottomMargin: 10)
        
        return bg
        
    }()
    
    lazy var goodInfoView:UIView = {
        
        let bg:UIButton = UIButton()
        bg.addTarget(self, action: #selector(goodsInfoClick), for: .touchUpInside)
        bg.backgroundColor = UIColor.white
        bg.sd_cornerRadius = SMALL_BTN_RADIUS

        let titlab = UILabel()
        titlab.text = "产品信息"
        titlab.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(rawValue: 0.2))
        titlab.textColor = UIColor.black
        bg.addSubview(titlab)
        
        let _  = titlab.sd_layout()?.leftSpaceToView(bg,16)!.heightIs(35)!.topSpaceToView(bg,5)!.rightSpaceToView(bg,16)
        
        
        let nameLab = UILabel()
        nameLab.text = self.order?.pdtName
        nameLab.font =  UIFont.commonFont
        nameLab.textColor = UIColor.black
        bg.addSubview(nameLab)
        
        let _  = nameLab.sd_layout()?.leftSpaceToView(bg,16)!.autoHeightRatio(0)!.topSpaceToView(titlab,10)!.rightSpaceToView(bg,16)
        nameLab.setMaxNumberOfLinesToShow(2)
        
        
        let infoLab = UILabel()
        let playtime = self.order?.playDate?.split(string: "T").first
        infoLab.text = "套餐类型: \(self.order?.proName ?? "")\n出发时间: \(playtime ?? "")\n\(self.order?.amountAdult ?? "0")成人 \(self.order?.amountChildren ?? "0")儿童"
        infoLab.font =  UIFont.commonFontSmaller
        infoLab.textColor = UIColor.textTitleColorBlack
        bg.addSubview(infoLab)
        
        let _  = infoLab.sd_layout()?.leftSpaceToView(bg,16)!.autoHeightRatio(0)!.topSpaceToView(nameLab,10)!.rightSpaceToView(bg,16)
        infoLab.setMaxNumberOfLinesToShow(4)
        
        
        let pricelab = UILabel()
        pricelab.text = "￥\(self.order?.amountAll ?? "0")"
        pricelab.font = UIFont.commonFontSmall
        pricelab.textColor = UIColor.black
        bg.addSubview(pricelab)
        let _ = pricelab.sd_layout()?.rightSpaceToView(bg,16)!.heightIs(20)?.bottomSpaceToView(bg,28)
        pricelab.setSingleLineAutoResizeWithMaxWidth(177)
        
        bg.setupAutoHeight(withBottomView: infoLab, bottomMargin: 10)
        return bg
        
        
    }()
    
    lazy var linkView:UIView = {
        
        let bg:UIView = UIView()
        bg.backgroundColor = UIColor.white
        bg.sd_cornerRadius = SMALL_BTN_RADIUS

        let titlab = UILabel()
        titlab.text = "联系人"
        titlab.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(rawValue: 0.2))
        titlab.textColor = UIColor.black
        bg.addSubview(titlab)
        
        let _  = titlab.sd_layout()?.leftSpaceToView(bg,16)!.heightIs(35)!.topSpaceToView(bg,5)!.rightSpaceToView(bg,16)
        
        
        var arr = [["title":"姓名","value":self.order?.linkName ?? ""],
                   ["title":"手机","value":self.order?.linkTel ?? ""],
                   ["title":"邮箱","value":self.order?.email ?? ""],

                  ]
        
        
    
        let linkView  = self.createVeiwWithArray(tits: arr )
       bg.addSubview(linkView)
        let _ = linkView.sd_layout()?.topSpaceToView(bg,40)?.autoHeightRatio(0)?.widthRatioToView(bg,1)
       bg.setupAutoHeight(withBottomView: linkView, bottomMargin: 10)
        
        return bg
        
    }()
    
    lazy var bottomView:UIView = {
        
        let bg = UIView()
        bg.backgroundColor = UIColor.white
        

        
        cancelBtn.addTarget(self, action: #selector(cancelClick), for: .touchUpInside)
        cancelBtn.setTitle("取消订单", for: .normal)
        cancelBtn.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
        cancelBtn.titleLabel?.font = UIFont.commonFontSmaller
        bg.addSubview(cancelBtn)
        let _ = cancelBtn.sd_layout()?.leftSpaceToView(bg,16)!.heightIs(35)!.centerYEqualToView(bg)
        cancelBtn.setupAutoSize(withHorizontalPadding: 1, buttonHeight: 35)
        
        
        bg.addSubview(rightBtn)
        rightBtn.addTarget(self, action: #selector(payBtnClick), for: .touchUpInside)
        rightBtn.sd_cornerRadius = MIDDLE_BTN_RADIUS
        let _ = rightBtn.sd_layout()?.widthIs(112)?.heightIs(MIDDLE_BTN_HEIGHT)?.rightSpaceToView(bg,16)?.centerYEqualToView(bg)
        rightBtn.gradientBtnMainColor()
        
        tlab.text = "立即支付"
        tlab.font = UIFont.commonFontSmall
        tlab.textColor = UIColor.white
        tlab.textAlignment = .center
        rightBtn.addSubview(tlab)
        let _ = tlab.sd_layout()?.spaceToSuperView(UIEdgeInsets.zero)
        

        
        return bg
        
    }()
    
    
    lazy var topView:UIView = {
        
        let bg = UIView()
        bg.frame = CGRect(x: 0, y: HT_StatusBarAndNavigationBarHeight, width: KScreenWidth, height: 135)
        bg.gradientBtnMainColor()

        let statusLab = UILabel()
        //        NEW("NEW", "新建订单"), FAILED("FAILED", "失效订单"), SUCCESS("SUCCESS", "成功订单"), FINISH("FINISH", "结束订单"), APPRAISED("APPRAISED", "已评价"); REFUNDING("REFUNDING", "退款中");

        
        statusLab.text = Constant.getOrderStatus(status: self.order!.orderStatus!, pay: self.order!.payStatus!)
        
        statusLab.font = UIFont.titleFont
        statusLab.textColor = UIColor.white
        bg.addSubview(statusLab)
        
        let _ = statusLab.sd_layout()?.leftSpaceToView(bg,24)!.topSpaceToView(bg,20)?.heightIs(22)?.rightSpaceToView(bg,90)
        let timeIcon = UIImageView()
        timeIcon.image = UIImage(named: "time")
        bg.addSubview(timeIcon)
        let _ = timeIcon.sd_layout()?.widthIs(15)?.heightIs(15)!.leftSpaceToView(bg,24)?.topSpaceToView(statusLab,20)
        
        let time = self.order?.payOverTime?.split(string: "T").first
        let time1 = self.order?.payOverTime?.split(string: "T")[1].split(string: ".").first
        let time2 = time! + " "+time1!
        let timeLab = UILabel()
        timeLab.text = "订单失效时间:\(time2)"
        timeLab.font = UIFont.smallerFont
        timeLab.textColor = UIColor.white
        bg.addSubview(timeLab)
        
        let _ = timeLab.sd_layout()?.leftSpaceToView(timeIcon,5)!.topSpaceToView(statusLab,20)?.heightIs(15)?.rightSpaceToView(bg,90)
        
        let priceLab = UILabel()
        priceLab.text = "￥\(self.order?.amountAll ?? "0")"
        priceLab.font = UIFont.commonFont
        priceLab.textColor = UIColor.white
        bg.addSubview(priceLab)
        
        let _ = priceLab.sd_layout()?.rightSpaceToView(bg,16)!.topSpaceToView(bg,35)?.heightIs(22)
        priceLab.setSingleLineAutoResizeWithMaxWidth(200)
        
        
        return bg
        
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.backgroundColor
        self.navigationView.setTitle("订单详情")
        
        self.view.addSubview(topView)
        bgScr.showsVerticalScrollIndicator = false
        bgScr.backgroundColor = UIColor.clear
        view.addSubview(self.bgScr)

        
        view.addSubview(self.bottomView)
        let _ = bottomView.sd_layout()?.widthRatioToView(view,1)!.bottomSpaceToView(view,HT_TabbarSafeBottomMargin)!.heightIs(60)
       
        
        self.bgScr.addSubview(self.orderInfoView)
        let _ = orderInfoView.sd_layout()?.widthRatioToView(self.bgScr,1)?.autoHeightRatio(0)?.topSpaceToView(self.bgScr,0)
        
        
        self.bgScr.addSubview(self.goodInfoView)
        let _ = goodInfoView.sd_layout()?.widthRatioToView(self.bgScr,1)?.autoHeightRatio(0)?.topSpaceToView(self.orderInfoView,10)
        
        
        self.bgScr.addSubview(self.linkView)
        let _ = linkView.sd_layout()?.widthRatioToView(self.bgScr,1)?.autoHeightRatio(0)?.topSpaceToView(goodInfoView,10)
        
        self.bgScr.setupAutoContentSize(withBottomView: linkView, bottomMargin: 0)
        
        if self.order!.orderStatus == "NEW" {
            
            cancelBtn.isHidden = false
            rightBtn.isHidden = false
            let _  = bgScr.sd_layout()?.topSpaceToView(topView,-30)!.leftSpaceToView(view,16)!.bottomSpaceToView(view,60+HT_TabbarSafeBottomMargin)!.rightSpaceToView(view,16)
            
        }else if self.order!.orderStatus == "FAILED"{

            self.bottomView.isHidden = true
            let _  = bgScr.sd_layout()?.topSpaceToView(topView,-30)!.leftSpaceToView(view,16)!.bottomSpaceToView(view,HT_TabbarSafeBottomMargin)!.rightSpaceToView(view,16)
            
        }else if self.order!.orderStatus == "SUCCESS"{
            
            rightBtn.isHidden = false
            cancelBtn.isHidden = true
            tlab.text = "退款"
            let _  = bgScr.sd_layout()?.topSpaceToView(topView,-30)!.leftSpaceToView(view,16)!.bottomSpaceToView(view,60+HT_TabbarSafeBottomMargin)!.rightSpaceToView(view,16)


        }else if self.order!.orderStatus == "FINISH"{
            
            if self.order!.payStatus == "PAYED" {
                
                rightBtn.isHidden = false
                cancelBtn.isHidden = true
                let tlab = UILabel()
                tlab.text = "评论"

                let _  = bgScr.sd_layout()?.topSpaceToView(topView,-30)!.leftSpaceToView(view,16)!.bottomSpaceToView(view,60+HT_TabbarSafeBottomMargin)!.rightSpaceToView(view,16)

                
            }else{

                self.bottomView.isHidden = true
                
            let _  = bgScr.sd_layout()?.topSpaceToView(topView,-30)!.leftSpaceToView(view,16)!.bottomSpaceToView(view,HT_TabbarSafeBottomMargin)!.rightSpaceToView(view,16)
            }
        }else if self.order!.orderStatus == "APPRAISED"{
            

            self.bottomView.isHidden = true
            let _  = bgScr.sd_layout()?.topSpaceToView(topView,-30)!.leftSpaceToView(view,16)!.bottomSpaceToView(view,HT_TabbarSafeBottomMargin)!.rightSpaceToView(view,16)
            
        }else if self.order!.orderStatus == "REFUNDING"{
            

            self.bottomView.isHidden = true
            let _  = bgScr.sd_layout()?.topSpaceToView(topView,-30)!.leftSpaceToView(view,16)!.bottomSpaceToView(view,HT_TabbarSafeBottomMargin)!.rightSpaceToView(view,16)
            
        }

        
    }
    

    
    func createVeiwWithArray(tits:Array<Dictionary<String,String>>) -> UIView{
        
        let bg = UIView()
        
    
        
        var temp = Array<UIView>()
        
        for index in 0 ..< tits.count{
            
            let dic = tits.get(at: index)
            let cell = self.createContentCellWith(for: dic!, tag: index+1000)
            bg.addSubview(cell)
            
            let  _ = cell.sd_layout()?.heightIs(30.5)

            temp.append(cell)
        }
        
        bg.setupAutoMarginFlowItems(temp, withPerRowItemsCount: 1, itemWidth: self.view.width, verticalMargin: 0, verticalEdgeInset: 0, horizontalEdgeInset: 0)
        
        return bg
    }
    
    func createContentCellWith(for dic:Dictionary<String,String>,tag:Int) -> UIView{
        
        let bg = UIView()
        let titLab = UILabel()
        bg.addSubview(titLab)
        titLab.font = UIFont.commonFontSmaller
        titLab.textColor = UIColor.init(hexString: "#999999")
        titLab.text  = dic["title"]
        let _ =  titLab.sd_layout()?.leftSpaceToView(bg,16)?.heightIs(20)?.widthIs(95-20)?.centerYEqualToView(bg)
        
        
        
        let valueLab = UILabel()
        bg.addSubview(valueLab)
        valueLab.text =  dic["value"]
        valueLab.font = UIFont.commonFontSmall
        valueLab.textColor = UIColor.textTitleColorBlack
        let _ =  valueLab.sd_layout()?.leftSpaceToView(titLab,16)?.heightIs(20)?.rightSpaceToView(bg,16)?.centerYEqualToView(bg)
        
        
        if titLab.text == "订单编号" {
         
            let copyBtn = UIButton()
            bg.addSubview(copyBtn)
            let _ = copyBtn.sd_layout()?.widthIs(48)!.heightIs(20)!.centerYEqualToView(bg)!.rightSpaceToView(bg,48)
            copyBtn.setTitle("复制", for: .normal)
            copyBtn.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
            copyBtn.sd_cornerRadius = 10
            copyBtn.layer.borderWidth = 1
            copyBtn.titleLabel?.font = UIFont.smallerFont
            copyBtn.layer.borderColor = UIColor.init(hexString: "#e5e5e5").cgColor
            copyBtn.addTarget(self, action: #selector(copyClick), for: .touchUpInside)
            
        }
        
        let line = UIView()
        bg.addSubview(line)
        line.backgroundColor = UIColor.lineColor
        let _ = line.sd_layout()?.widthRatioToView(bg,1)?.heightIs(1)?.bottomSpaceToView(bg,0)
        
        line.isHidden = true
        
        return bg
    }
    
    @objc func goodsInfoClick(){
        
        API.playDetail(params: ["id":self.order!.pdtId!]) { (result) in
            
            API.productCommentList(params: ["page":"1",
                                            "pdtId":self.order!.pdtId!]) { (pageVo) in
                
                                                
                                                let page = pageVo as! Page<CommentVo>
                                                let dvc = ProductDetailVC()
                                                dvc.product = (result as! ProductVo)
                                                if page.list.count > 0{
                                                    
                                                    dvc.commentVo = page.list.first
                                                }
                                                PUSH(from: self, to: dvc)
            }
            

        }
    }
    @objc func cancelClick(){
        
        API.orderCancel(params: ["orderNo":self.order!.orderNo!,
                                 ]) { (result) in
            
            
                                    ToastUtil.showHUDSuccess(msg: "订单取消成功")
        }
        
    }
    @objc func copyClick(){
        
        let pasteboard = UIPasteboard.general
        pasteboard.string = self.order?.orderNo
        ToastUtil.showHUDSuccess(msg: "订单号已成功复制到剪贴板")
    }
    
    @objc func payBtnClick(btn:UIButton){
        
        
        if tlab.text == "立即支付"  {
            
            let payvc = PayViewController()
            payvc.order = self.order
            PUSH(from: self, to: payvc)
            
        }else if tlab.text == "评论"{
            
            self.showCommentAlert()
            
        }else if tlab.text == "退款"{
            
            API.orderCancel(params: ["orderNo":self.order!.orderNo!,
                                     ]) { (result) in
                
                
                                        ToastUtil.showHUDSuccess(msg: "申请退款成功")
            }
        }

    }
    let bg = UIView()
    let inputV = GCPlaceholderTextView()
    
    @objc func showCommentAlert() {
         
         self.view.addSubview(bg)
         let _  = bg.sd_layout()?.spaceToSuperView(.zero)

         let bgImgv = UIImageView()
         bgImgv.alpha = 0.5
         bgImgv.backgroundColor = UIColor.init(patternImage: UIImage(named: "paybg")!)
         bg.addSubview(bgImgv)
         let _ = bgImgv.sd_layout()?.spaceToSuperView(.zero)
         
         let bg2 = UIView()
     bg2.backgroundColor = UIColor.white
         bg.addSubview(bg2)
         let _ = bg2.sd_layout()?.bottomSpaceToView(bg,0)?.widthRatioToView(bg,1)?.heightIs(166)
     
     bg2.addSubview(inputV)
     inputV.placeholder = "发表评论"
     inputV.sd_cornerRadius = 3
     inputV.font = UIFont.commonFontSmall
     inputV.textColor = UIColor.textTitleColorBlack
     let _ = inputV.sd_layout()?.leftSpaceToView(bg2,16)!.rightSpaceToView(bg2,16)!.heightIs(90)!.topSpaceToView(bg2,25)
     inputV.layer.borderColor = UIColor.textTitleColorBlack.cgColor
     inputV.layer.borderWidth = 0.5
     
     let sendBtn = UIButton()
     sendBtn.setTitle("发送", for: .normal)
     sendBtn.addTarget(self, action: #selector(sendBtnClick), for: .touchUpInside)
     sendBtn.setTitleColor(UIColor.btnMainColor, for: .normal)
     sendBtn.titleLabel?.font = UIFont.commonFontSmall
     bg2.addSubview(sendBtn)
     
     let _ = sendBtn.sd_layout()?.rightSpaceToView(bg2,16)!.heightIs(28)!.widthIs(38)!.topSpaceToView(inputV,5)
     
     let cancelBtn = UIButton()
     cancelBtn.setTitle("取消", for: .normal)
     cancelBtn.addTarget(self, action: #selector(cancelBtnClick), for: .touchUpInside)
     cancelBtn.setTitleColor(UIColor.GP_Red_Color, for: .normal)
     cancelBtn.titleLabel?.font = UIFont.commonFontSmall
     bg2.addSubview(cancelBtn)
     
     let _ = cancelBtn.sd_layout()?.leftSpaceToView(bg2,16)!.heightIs(28)!.widthIs(38)!.topSpaceToView(inputV,5)
     
     
     
         
     }
    
    @objc func sendBtnClick(){
        
          if SPUtil.init().loginStatus == 0 {
              
              APP.backToVC = self
              PUSH(from: self, to: LoginViewController())
              return
          }
          if SPUtil.init().mobile.count == 0 {
              
              APP.backToVC = self
              PUSH(from: self, to: BindPhoneVC())
              return
        
          }

        if inputV.text.count == 0 {
            
            ToastUtil.showHUDWarn(msg: "随便写点什么吧")
            return
        }
    
        API.orderComment(params: [
            "orderNo":self.order!.orderNo!,
            "remark":inputV.text!]) { (result) in
            
                                        ToastUtil.show(msg: "评论已提交")
                                        self.bg.removeFromSuperview()
                                        

        }
        
    }
    @objc func cancelBtnClick(){
        
        bg.removeFromSuperview()
    }
}
